package org.leetcode.middle.leetcode151;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public String reverseWords(String s)
    {
        String[] strArray = s.split(" ");

        List<String> list = new ArrayList<>();

        for (String s1:strArray) {
            if (s1!=" " && s1!="")
            {
                list.add(s1);
            }
        }

        strArray=new String[list.size()];

        for (int i = 0; i < list.size(); i++) {
            strArray[i]=list.get(i);
        }


        int left = 0;
        int right = strArray.length-1;

        String temp ="";
        while (right>left)
        {
            temp=strArray[left];
            strArray[left]=strArray[right];
            strArray[right]=temp;

            right--;

            left++;
        }

        String result ="";

        for (int i = 0; i < strArray.length; i++) {

            if (i<strArray.length-1)
            {
                result=result+strArray[i]+" ";
            }else {
                result=result+strArray[i];
            }

        }


        return result;
    }

    public static void main(String[] args) {
//        String test = "zhang    zhen ";
//        String[] s = test.split(" ");
//        System.out.println(s.length);

        Solution solution = new Solution();
        String res = solution.reverseWords("  hello world  ");
        System.out.println(res);

    }
}
